package com.ilop.sthome.ui.activity.scene;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.example.common.base.BaseBindActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.utils.CoderUtils;
import com.example.common.view.WheelView;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivitySetHumitureBinding;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author skygge
 * @date 2020-02-04.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：设置温湿度输入动作（触发条件）
 */
public class SettingHumitureActivity extends BaseBindActivity<ActivitySetHumitureBinding> {

    private boolean isAdd;
    private boolean isUpdate;
    private boolean isDefeat;
    private String mRecommendId;
    private DeviceInfoBean mDevice;
    private int mType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_humiture;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mType = getIntent().getIntExtra(CommonId.KEY_MESSAGE_TYPE, -1);
        isAdd = getIntent().getBooleanExtra(CommonId.KEY_ADD_NEW, false);
        isUpdate = getIntent().getBooleanExtra(CommonId.KEY_UPDATE, false);
        mDevice = (DeviceInfoBean) getIntent().getSerializableExtra(CommonId.KEY_DEVICE);

        mRecommendId = getIntent().getStringExtra(CommonId.KEY_DEVICE_TYPE);
        isDefeat = getIntent().getBooleanExtra(CommonId.KEY_MESSAGE, false);
    }

    @Override
    protected void initView() {
        super.initView();
        mDBind.humNum.setCyclic(true);
        mDBind.tempNum.setCyclic(true);
        ArrayList<String> item_temp = new ArrayList<>();
        ArrayList<String> item_hum = new ArrayList<>();
        String[] mStyle = getResources().getStringArray(R.array.thtrigger_style);
        ArrayList<String> item_style = new ArrayList<>(Arrays.asList(mStyle));

        for (int i = -40; i <= 90; i ++) {
            String item = String.valueOf(i);
            item_temp.add(item+"℃");
        }

        for (int i = 1; i < 100; i ++) {
            String item = String.valueOf(i);
            item_hum.add(item+"%");
        }

        mDBind.tempStyle.setAdapter(new NumberAdapter(item_style));
        mDBind.humStyle.setAdapter(new NumberAdapter(item_style));
        mDBind.tempNum.setAdapter(new NumberAdapter(item_temp));
        mDBind.humNum.setAdapter(new NumberAdapter(item_hum));

        switch (mType){
            case 0:
            case 1:
                mDBind.tempTitle.setText(mType == 0?getString(R.string.temp_lower_than_what_trigger):getString(R.string.temp_higher_than_what_trigger));
                mDBind.tempStyle.setVisibility(View.GONE);
                mDBind.setHumidity.setVisibility(View.GONE);
                break;
            case 2:
            case 3:
                mDBind.tempTitle.setText(mType == 2?getString(R.string.hum_lower_than_what_trigger):getString(R.string.hum_higher_than_what_trigger));
                mDBind.humStyle.setVisibility(View.GONE);
                mDBind.setTemperature.setVisibility(View.GONE);
                break;
        }

        if (isAdd){
            mDBind.tempNum.setCurrentItem(65);
            mDBind.humNum.setCurrentItem(49);
        }
        if (!TextUtils.isEmpty(mRecommendId)){
            if ("0D".equals(mRecommendId)){
                mType = 0;
                mDBind.setHumidity.setVisibility(View.GONE);
            }else if ("0E".equals(mRecommendId)){
                mType = 2;
                mDBind.setTemperature.setVisibility(View.GONE);
            }
        }

        if (isUpdate && !isDefeat) mDBind.humitureDelete.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initData() {
        super.initData();
        if (isUpdate){
            getCurrentNum(mDevice.getDevice_status());
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivBack.setOnClickListener(v -> finish());
        mDBind.tvSaveHumiture.setOnClickListener(v -> {
            int a = mDBind.tempNum.getCurrentItem();
            String temp = Integer.toHexString(a<40 ? 256+(a-40) : a-40).toUpperCase();
            String hum =Integer.toHexString(mDBind.humNum.getCurrentItem()+1).toUpperCase();
            String tempCode = CoderUtils.setCodeSupplement1Byte(temp);
            String humCode = CoderUtils.setCodeSupplement1Byte(hum);
            String finalCode = getFinalCode(tempCode, humCode);
            mDevice.setDevice_status(finalCode);
            if (isAdd){
                addNewAuto();
            }else {
                if (!isUpdate) {
                    LiveDataBus.get().with(CommonId.INPUT_CONDITION).setValue(mDevice);
                } else {
                    LiveDataBus.get().with(CommonId.INPUT_UPDATE).setValue(mDevice);
                }
            }
            finish();
        });

        mDBind.humitureDelete.setOnClickListener(v -> {
            LiveDataBus.get().with(CommonId.DELETE_CONDITION).setValue(true);
            finish();
        });

        mDBind.tempStyle.addScrollingListener(new WheelView.OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                mType = wheel.getCurrentItem();
            }
        });

        mDBind.humStyle.addScrollingListener(new WheelView.OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                mType = wheel.getCurrentItem() + 2;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(mDevice.getSubdeviceName())){
            String title = getString(SmartDevice.getType(mDevice.getDevice_type()).getTypeStrId()) + mDevice.getDevice_ID();
            mDBind.tvHumitureTitle.setText(title);
        }else {
            mDBind.tvHumitureTitle.setText(mDevice.getSubdeviceName());
        }
    }

    private void addNewAuto(){
        AutomationBean mAuto = new AutomationBean();
        List<DeviceInfoBean> mDeviceList = new ArrayList<>();
        mDeviceList.add(mDevice);
        mAuto.setDeviceName(mDevice.getDeviceName());
        mAuto.setInputList(mDeviceList);
        Intent intent = new Intent();
        intent.setClass(mContext, ChooseActionActivity.class);
        intent.putExtra(CommonId.KEY_ADD_SCENE, true);
        intent.putExtra(CommonId.KEY_INPUT, false);
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDevice.getDeviceName());
        intent.putExtra(CommonId.KEY_AUTOMATION, mAuto);
        startActivity(intent);
    }

    private String getFinalCode(String tempCode, String humCode){
        switch (mType){
            case 0:
                return "11" + tempCode;
            case 1:
                return "01" + tempCode;
            case 2:
                return "41" + humCode;
            case 3:
                return "31" + humCode;
            default:
                return null;
        }
    }

    private void getCurrentNum(String status){
        if ("1100".equals(status)){
            mDBind.tempStyle.setCurrentItem(0);
            mDBind.tempNum.setCurrentItem(40);
        }else if ("410F".equals(status)){
            mDBind.humStyle.setCurrentItem(0);
            mDBind.humNum.setCurrentItem(14);
        }else {
            String action = status.substring(0, 2);
            String code = status.substring(2, 4);
            switch (action){
                case "01"://温度高于-上限
                    mType = 1;
                    getTempText(false, code);
                    break;
                case "11"://温度低于-下限
                    mType = 0;
                    getTempText(true, code);
                    break;
                case "31"://湿度高于-上限
                    mType = 3;
                    getHumText(false, code);
                    break;
                case "41"://湿度低于-下限
                    mType = 2;
                    getHumText(true, code);
                    break;
            }
        }
    }

    private void getTempText(boolean isLow, String tempCode){
        if (isLow){
            int temp = Integer.parseInt(tempCode, 16);
            if (temp > 128) {
                temp = 256 - temp;
                mDBind.tempNum.setCurrentItem(40 - temp);
            }else {
                mDBind.tempNum.setCurrentItem(temp + 40);
            }
            mDBind.tempStyle.setCurrentItem(0);
        }else {
            int temp = Integer.parseInt(tempCode, 16);
            if (temp > 128) {
                temp = 256 - temp;
                mDBind.tempNum.setCurrentItem(40 - temp);
            }else {
                mDBind.tempNum.setCurrentItem(temp + 40);
            }
            mDBind.tempStyle.setCurrentItem(1);
        }
        mDBind.setHumidity.setVisibility(View.GONE);
    }

    private void getHumText(boolean isLow, String humCode){
        mDBind.humStyle.setCurrentItem(isLow ? 0: 1);
        mDBind.humNum.setCurrentItem(Integer.parseInt(humCode, 16)-1);
        mDBind.setTemperature.setVisibility(View.GONE);
    }

    private static class NumberAdapter extends WheelView.WheelArrayAdapter<String> {

        NumberAdapter(ArrayList<String> items) {
            super(items);
        }
    }
}
